package com.xy.p2p.action.admin;



import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xy.common.page.Pagination;
import com.xy.common.util.DictUtils;
import com.xy.common.web.CookieUtils;
import com.xy.core.web.WebErrors;
import com.xy.p2p.model.Tfinanceinfo;
import com.xy.p2p.model.Tmember;
import com.xy.p2p.model.Tmemberassetaccount;
import com.xy.p2p.model.Tuser;
import com.xy.p2p.model.Twidrapp;
import com.xy.p2p.service.TfinanceinfoService;



@Controller
public class TfinanceinfoAction{
	private static final Logger log = LoggerFactory.getLogger(TfinanceinfoAction.class);
	public TfinanceinfoAction() {
	}
 
 
 	/**
	 * 融资标的信息表新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tfinanceinfoAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		model.addAttribute("tfinanceinfo", new Tfinanceinfo());
        setDict(model);
		return "tfinanceinfoEdit";
	}

	/**
	 * 融资标的信息表新增保存
	 * 
	 * @param tfinanceinfo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/o_tfinanceinfoSave.do")
	public String save(Tfinanceinfo tfinanceinfo, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(tfinanceinfo, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		tfinanceinfo = tfinanceinfoService.save(tfinanceinfo);
		if(null!=request.getParameter("opr")){

			return "redirect:v_tfinanceinfoList.do";
		}else{
			return "redirect:v_tfinanceinfoList2.do";
		}
		
//		if(8==tfinanceinfo.getTargettype())
//			return "redirect:v_tfinanceinfoList2.do";
	}

	/**
	 * 融资标的信息表删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("o_tfinanceinfoDelete.do")
	public String delete(long[] ids) {
		if (ids != null) {
			for (long id : ids) {
				tfinanceinfoService.remove(id);
			}
		}
		return "redirect:v_tfinanceinfoList.do";
	}

	/**
	 * 融资标的信息表编辑页面
	 * 
	 * @param fiid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tfinanceinfoEdit.do")
	public String edit(long fiid, HttpServletRequest request, ModelMap model,String opr) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		model.addAttribute("tfinanceinfo", tfinanceinfo);
		model.addAttribute("opr", opr);
        setDict(model);
		return "tfinanceinfoEdit";
	}
	
	/**
	 * 融资标的信息审核
	 * @param fiid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tfinanceinfoAudit.do")
	public String audit(long fiid, HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		model.addAttribute("tfinanceinfo", tfinanceinfo);
        setDict(model);
		return "tfinanceinfoAudit";
	}
	
	/**
	 * 融资标的审核提交
	 * @param opr
	 * @param fiid
	 * @param opnion
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tfinanceinfoAuditSubmit.do")
	public String auditSubmit(String opr,long fiid,String opnion, HttpServletRequest request, ModelMap model) {
		Tuser tuser = (Tuser)request.getSession().getAttribute(TuserAction.AUTH_KEY);
		if(null==tfinanceinfoService.audit(fiid, opr, opnion, tuser))
			return "redirect:v_tfinanceinfoList.do";
		model.addAttribute("tfinanceinfo", tfinanceinfoService.audit(fiid, opr, opnion, tuser));
        setDict(model);
		return "tfinanceinfoView";
	}
	
	/**
	 * 融资标的放款
	 * @param fiid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tfinanceinfoLoan.do")
	public String loan(long fiid, HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		model.addAttribute("tfinanceinfo", tfinanceinfo);
        setDict(model);
//        MailAction mailaction = new MailAction();
//        mailaction.mail(fiid);
		return "tfinanceinfoLoan";
	}

	/**
	 * 放款提交
	 * @param opr
	 * @param fiid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tfinanceinfoLoanSubmit.do")
	public String LoanSubmit(String opr,long fiid,HttpServletRequest request,HttpServletResponse response, ModelMap model) {
		Tuser tuser = (Tuser)request.getSession().getAttribute(TuserAction.AUTH_KEY);
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		if(null==tfinanceinfoService.loan(tfinanceinfo, opr, tuser)){
			try {
				response.getWriter().write("<script type='text/javascript'>alert('还款错误,请保证余额足够并且不能提前还款...')</script>");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "redirect:v_tfinanceinfoList.do";
		}
		model.addAttribute("tfinanceinfo", tfinanceinfoService.loan(tfinanceinfo, opr,tuser));
        setDict(model);
		return "redirect:v_tfinanceinfoList.do";
	}
	
	@RequestMapping("v_tfinanceinfoToPay.do")
	public String ToPay (long fiid, HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		model.addAttribute("tfinanceinfo", tfinanceinfo);
        setDict(model);
//        MailAction mailaction = new MailAction();
//        mailaction.mail(fiid);
		return "tfinanceinfoPay";
	}
	
	
	@RequestMapping("v_tfinanceinfoPaySubmit.do")
	public String PaySubmit (long fiid, HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
//		if(new Date().getTime()<tfinanceinfo.getNrdate().getTime()){
//			model.addAttribute("msg", "还未到还款的日期...");
//			return "forward:v_tfinanceinfoToPay.do";
//		}
		Tmember tmember = tfinanceinfo.getTmember();
		Set<Tmemberassetaccount> accountSet = tmember.getTmemberassetaccounts();
		for(Tmemberassetaccount t : accountSet){
			if(tfinanceinfo.getSubpri()+tfinanceinfo.getAlino()+tfinanceinfo.getMftba()>t.getBalance()){
				model.addAttribute("msg", "余额不足,请通知用户充值...");
				return "forward:v_tfinanceinfoToPay.do";
			}
		}
		model.addAttribute("tfinanceinfo", tfinanceinfo);
		if(null==tfinanceinfoService.pay(tfinanceinfo, (Tuser)request.getSession().getAttribute(TuserAction.AUTH_KEY))){
			model.addAttribute("msg", "还款失败, 请联系管理员...");
			return "forward:v_tfinanceinfoToPay.do";
		}
        return "forward:v_tfinanceinfoList.do";
	}
	
	/**
	 * 融资标的信息表详情
	 * 
	 * @param fiid
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tfinanceinfoDetail.do")
	public String detail(long fiid, HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		model.addAttribute("tfinanceinfo", tfinanceinfo);
        setDict(model);
		return "tfinanceinfoView";
	}
	/**
	 * 余额贷信息表详情
	 */
	@RequestMapping("v_tfinanceinfoDetail2.do")
	public String detail1(long fiid, HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		model.addAttribute("tfinanceinfo", tfinanceinfo);
		model.addAttribute("xopr",2);
        setDict(model);
		return "tfinanceinfoView";
	}
	
	

	/**
	 * 融资标的信息表查询（分页）
	 * 
	 * @param tfinanceinfo
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tfinanceinfoList.do")
	public String listPage(Tfinanceinfo tfinanceinfo, Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		Pagination pagination = tfinanceinfoService.getTfinanceinfoByPage(toMap(tfinanceinfo),
				pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
        setDict(model);
		return "tfinanceinfoList";
	}

	/**
	 * 融资标的信息表查询
	 * 
	 * @param tfinanceinfo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tfinanceinfoList1.do")
	public String list(Tfinanceinfo tfinanceinfo, HttpServletRequest request, ModelMap model) {
		List<Tfinanceinfo> list = tfinanceinfoService.getTfinanceinfo(toMap(tfinanceinfo));
		model.addAttribute("list", list);
        setDict(model);
		return "tfinanceinfoList";
	}
	/*
	 * 余额贷
	 * */
	@RequestMapping("v_tfinanceinfoList2.do")
	public String list2(Tfinanceinfo tfinanceinfo, Integer pageNo,HttpServletRequest request, ModelMap model) {
		tfinanceinfo.setTargettype(8);
		if (pageNo == null)
			pageNo = 1;
		Pagination pagination = tfinanceinfoService.getTfinanceinfoByPage(toMap(tfinanceinfo),
				pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
        setDict(model);
        model.addAttribute("now",new Date());
		return "tfinanceinfoList2";
	}
	/*
	 * 修改
	 * */
	@RequestMapping("v_tfinanceinfoEdit2.do")
	public String edit2(long fiid, HttpServletRequest request, ModelMap model) {
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		model.addAttribute("tfinanceinfo", tfinanceinfo);
        setDict(model);
		return "tfinanceinfoEdit2";
	}
	
	@RequestMapping("v_tfinanceinfoYEDPay.do")
	public String YEDPay(long fiid,HttpServletRequest request,ModelMap model){
		Tfinanceinfo tfinanceinfo = tfinanceinfoService.get(fiid);
		tfinanceinfoService.YEDPay(tfinanceinfo);
		setDict(model);
		return "forward:v_tfinanceinfoList2.do";
	}
	
	@RequestMapping("v_tfinanceinfoSendmail.do")
	public String Sendmail(long fiid,HttpServletRequest request,ModelMap model){
		tfinanceinfoService.sendFullMail(fiid);
		setDict(model);
		return "forward:v_tfinanceinfoList2.do";
	}

 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param tfinanceinfo
	 * @return
	 */	private Map<String,Object> toMap(Tfinanceinfo tfinanceinfo){
		Map<String,Object> map=new HashMap<String, Object>();
      		if(tfinanceinfo.getFiid()!=null&&!tfinanceinfo.getFiid().equals("")){
			map.put("fiid", tfinanceinfo.getFiid());
		}
		if(tfinanceinfo.getTmember()!=null&&!tfinanceinfo.getTmember().equals("")){
			map.put("Tmember", tfinanceinfo.getTmember());
		}
		if(tfinanceinfo.getFinancekey()!=null&&!tfinanceinfo.getFinancekey().equals("")){
			map.put("financekey", tfinanceinfo.getFinancekey());
		}
		if(tfinanceinfo.getFinanceuse()!=null&&!tfinanceinfo.getFinanceuse().equals("")){
			map.put("financeuse", tfinanceinfo.getFinanceuse());
		}
		if(tfinanceinfo.getFinanceamount()!=null&&!tfinanceinfo.getFinanceamount().equals("")){
			map.put("financeamount", tfinanceinfo.getFinanceamount());
		}
		if(tfinanceinfo.getFinanceallotedtime()!=null&&!tfinanceinfo.getFinanceallotedtime().equals("")){
			map.put("financeallotedtime", tfinanceinfo.getFinanceallotedtime());
		}
		if(tfinanceinfo.getFinancepa()!=null&&!tfinanceinfo.getFinancepa().equals("")){
			map.put("financepa", tfinanceinfo.getFinancepa());
		}
		if(tfinanceinfo.getRepaymentperiod()!=null&&!tfinanceinfo.getRepaymentperiod().equals("")){
			map.put("repaymentperiod", tfinanceinfo.getRepaymentperiod());
		}
		if(tfinanceinfo.getRepaymentmod()!=null&&!tfinanceinfo.getRepaymentmod().equals("")){
			map.put("repaymentmod", tfinanceinfo.getRepaymentmod());
		}
		if(tfinanceinfo.getFinancelimit()!=null&&!tfinanceinfo.getFinancelimit().equals("")){
			map.put("financelimit", tfinanceinfo.getFinancelimit());
		}
		if(tfinanceinfo.getFinancedescription()!=null&&!tfinanceinfo.getFinancedescription().equals("")){
			map.put("financedescription", tfinanceinfo.getFinancedescription());
		}
		if(tfinanceinfo.getStatus()!=null&&!tfinanceinfo.getStatus().equals("")){
			map.put("status", tfinanceinfo.getStatus());
		}
		if(tfinanceinfo.getItfdate()!=null&&!tfinanceinfo.getItfdate().equals("")){
			map.put("itfdate", tfinanceinfo.getItfdate());
		}
		if(tfinanceinfo.getNrdate()!=null&&!tfinanceinfo.getNrdate().equals("")){
			map.put("nrdate", tfinanceinfo.getNrdate());
		}
		if(tfinanceinfo.getPlsf()!=null&&!tfinanceinfo.getPlsf().equals("")){
			map.put("plsf", tfinanceinfo.getPlsf());
		}
		if(tfinanceinfo.getMfrl()!=null&&!tfinanceinfo.getMfrl().equals("")){
			map.put("mfrl", tfinanceinfo.getMfrl());
		}
		if(tfinanceinfo.getSubpri()!=null&&!tfinanceinfo.getSubpri().equals("")){
			map.put("subpri", tfinanceinfo.getSubpri());
		}
		if(tfinanceinfo.getAlino()!=null&&!tfinanceinfo.getAlino().equals("")){
			map.put("alino", tfinanceinfo.getAlino());
		}
		if(tfinanceinfo.getMftba()!=null&&!tfinanceinfo.getMftba().equals("")){
			map.put("mftba", tfinanceinfo.getMftba());
		}      
		if(tfinanceinfo.getTargettype()!=null&&!tfinanceinfo.getTargettype().equals("")){
			map.put("targettype", tfinanceinfo.getTargettype());
		}
		if(tfinanceinfo.getRemark()!=null&&!tfinanceinfo.getRemark().equals("")){
			map.put("remark", tfinanceinfo.getRemark());
		}
		if(tfinanceinfo.getApplicationdate()!=null&&!tfinanceinfo.getApplicationdate().equals("")){
			map.put("applicationdate", tfinanceinfo.getApplicationdate());
		} 
		if(tfinanceinfo.getRewardrate()!=null&&!tfinanceinfo.getRewardrate().equals("")){
			map.put("rewardrate", tfinanceinfo.getRewardrate());
		} 
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
      model.addAttribute("repaymentperiodMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_REPAYMENTPERIOD));
      model.addAttribute("repaymentmodMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_REPAYMENTMOD));
      model.addAttribute("statusMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_STATUS));		
      model.addAttribute("targettypeMap", DictUtils.getDictByType(DictUtils.TFINANCEINFO_TARGETTYPE));	
	}

	/**
	 * 数据校验
	 * @param model
	 */
	private WebErrors validateSave(Tfinanceinfo tfinanceinfo, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		/**if (errors.ifOutOfLength(username, "username", 1, 100)) {
			return errors;
		}  */    
		return errors;
	}

   
      
	@Resource
	private TfinanceinfoService tfinanceinfoService;   
}